package com.zhenwgang.listen_books.servlet.publish;

import com.zhenwgang.listen_books.repository.TrackRepo;
import com.zhenwgang.listen_books.view_object.TrackContent;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Violet
 * @date 2022/07/21 21:51
 **/
@WebServlet("/track")
public class TrackServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int tid = Integer.parseInt(req.getParameter("tid"));
        TrackRepo trackRepo = new TrackRepo();
        TrackContent trackContent = trackRepo.selectContentByTid(tid);

        resp.setContentType(trackContent.type);
        ServletOutputStream os = resp.getOutputStream();

        byte[] buf = new byte[4096];
        while (true) {
            int n = trackContent.content.read(buf);
            if (n == -1) {
                break;
            }

            os.write(buf, 0, n);
        }

        os.flush();
        trackContent.content.close();
    }
}